package com.dinero.pagecontents.activity

import android.graphics.Color
import android.util.Log
import android.view.Gravity
import android.view.KeyEvent
import com.android.basekt.base.BaseDataBindingConfig
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.dinero.pagecontents.R
import com.dinero.pagecontents.adapter.CertificationInputItemAdapter
import com.dinero.pagecontents.base.BaseActivity
import com.dinero.pagecontents.bean.Matched
import com.dinero.pagecontents.databinding.ActivityCertifyInformationBinding
import com.dinero.pagecontents.view.TipsDialog
import com.dinero.pagecontents.view.WenDialog
import com.dinero.pagecontents.viewmodel.CertifyPersonInformationViewModel
import java.util.*

/**
 * @Created on 2021/12/21 19:53
 * @Author 工作信息
 * @Describe
 */
open class CertifyPersonInformationActivity :
    BaseActivity<ActivityCertifyInformationBinding, CertifyPersonInformationViewModel>() {
    var mProId: String = ""
    var mComplete: String = ""

    var mCurAdapterSelectPosition = 0
    val mAdapter: CertificationInputItemAdapter by lazy {
        CertificationInputItemAdapter().apply {
            addChildClickViewIds(R.id.ll_other)
            addChildClickViewIds(R.id.ll_root)
            addChildClickViewIds(R.id.img_wenhao)
            setOnItemChildClickListener { _, view, position ->

                if (view.id == R.id.ll_root) {

                    KeyboardUtils.hideSoftInput(view)
                } else if (view.id == R.id.img_wenhao) {
                    wenDialog.show(supportFragmentManager, "")
                } else if (view.id == R.id.ll_other) {

                    var type = mAdapter.data[position].intent
                    var name = mAdapter.data[position].thanked
                    var emuaDatas = mAdapter.data[position].matched
                    Log.i("BaseActivity", "adapter====> type:${type},name:${name}")
                    view.requestFocus()
                    mCurAdapterSelectPosition = position

                    if (type == "F") {

                        KeyboardUtils.hideSoftInput(view)
                        mViewModel.mBrithDayView.show()
                    } else if (type == "B") {
                        KeyboardUtils.hideSoftInput(view)
                        mViewModel.showEnumView(emuaDatas)
                    } else if (type == "C") {
                        KeyboardUtils.hideSoftInput(view)
                        mViewModel.showEnumView(emuaDatas)
                    }

                }

            }
        }
    }

    override fun initView() {
        BarUtils.setStatusBarLightMode(this, false)
        mBinding.apply {
            viewModel = mViewModel
            recycleView.adapter = mAdapter
        }

        mProId = intent.getStringExtra("proId").toString()
        mComplete = intent.getStringExtra("complete").toString()
        var ordId = intent.getStringExtra("ordId")

        mViewModel.apply {
            mCurViewType = getViewType()
            mOrdId.value = ordId
            mProId.value = this@CertifyPersonInformationActivity.mProId
            mContext = this@CertifyPersonInformationActivity
            mBrithDayContent.observe(this@CertifyPersonInformationActivity) {
                mAdapter.data[mCurAdapterSelectPosition].howqw = it
                mAdapter.notifyItemChanged(mCurAdapterSelectPosition)
            }
            mInformationDatas.observe(this@CertifyPersonInformationActivity) {
                mAdapter.setNewInstance(it)
                if (getViewType() == "bank") {
                    for (index in 0 until it.size) {
                        if (it[index].between == "cardNo") {
                            curBankNoIndex = index
                        }
                    }
                }
            }
            mSelectContent.observe(this@CertifyPersonInformationActivity) {
                var curItemData = mAdapter.data[mCurAdapterSelectPosition]
                curItemData.selData.attended = it.attended
                curItemData.selData.oxford = it.oxford
                mAdapter.notifyItemChanged(mCurAdapterSelectPosition)
                if (getViewType() == "bank" && curItemData.between == "bankType") {
                    curItemData.matched.forEach { match ->
                        if (match.oxford == it.oxford) {
                            curBankType = match
                        }
                    }
                    notifyBankNoHint()
                } else if (getViewType() == "bank" && curItemData.between == "bankCode") {
                    curItemData.matched.forEach { match ->
                        if (match.oxford == it.oxford) {
                            curBank = match
                        }
                    }
                    notifyBankNoHint()
                }
            }


            bankType.observe(this@CertifyPersonInformationActivity) {
                if (getViewType() == "bank") {
                    curBankType = it
                    notifyBankNoHint()
                }

            }

            bankCode.observe(this@CertifyPersonInformationActivity) {
                if (getViewType() == "bank") {
                    curBank = it
                    notifyBankNoHint()
                }
            }
        }
    }

    private fun notifyBankNoHint() {
        var hint = ""
        var maxLength = 999
        curBankType?.let {
            if (it.oxford == "1") {
                hint = it.thanked
                maxLength = 16
                mAdapter.isShowWen = false
            } else if (it.oxford == "2") {
                maxLength = 18
                var tempHint = it.thanked
                hint = it.thanked
                mAdapter.isShowWen = true
                curBank?.let { bank ->
                    if (bank.oxford.length > 3) {
                        hint = tempHint + bank.oxford.subSequence(
                            bank.oxford.length - 3,
                            bank.oxford.length
                        )
                    }
                }
            }
        }
        curBankNoIndex?.let {
            mAdapter.data[it].edHint = hint
            mAdapter.data[it].thanked = hint
            mAdapter.data[it].edMaxLenth = maxLength
            mAdapter.notifyItemChanged(it)
        }

    }

    /**
     * 当前选择的银行卡类型
     */
    var curBankType: Matched? = null

    /**
     * 当前选择的银行卡
     */
    var curBank: Matched? = null

    var curBankNoIndex: Int? = null


    open fun getViewType(): String {
        return "person"
    }

    val banckCardConfirmDialog: TipsDialog by lazy {
        TipsDialog(
            title = "Confirme que los digitos de la CLABE proporcionada son correctos",
            left = "Modificar",
            right = "Continuar",
            titleGravity = Gravity.LEFT,
            titleColor = Color.parseColor("#ff999999"),
            tipsGravity = Gravity.LEFT,
            tipsColor = Color.parseColor("#ff333333"),
        ).apply {
            setRightListener {
                mViewModel.submitDataInfo()
            }
        }
    }

    val wenDialog: WenDialog by lazy {
        WenDialog().apply {
            setRightListener {
                mViewModel.submitDataInfo()
            }
        }
    }

    override fun initData() {
        var title = intent.getStringExtra("title")
        title?.let {
            mViewModel.mTitleContent.value = it
        }

        mProId.let { mViewModel.getData(it) }

        mViewModel.banckCardConfirmEvent.observe(this) { content ->
            if (!content.isNullOrEmpty()) {
                banckCardConfirmDialog.showNow(supportFragmentManager, "tips")

                if (curBankType != null) {
                    curBankType?.let {
                        if (it.oxford == "1") {
                            banckCardConfirmDialog.setTipsTitle("Confirme que el número de tarjeta bancaria proporcionado sea correcto")
                            banckCardConfirmDialog.setTipsContent(getCardNoContent(content, false))
                        } else {
                            banckCardConfirmDialog.setTipsTitle("Confirme que los digitos de la CLABE proporcionada son correctos")
                            banckCardConfirmDialog.setTipsContent(getCardNoContent(content, true))
                        }
                    }
                } else {
                    banckCardConfirmDialog.setTipsTitle("Confirme que el número de tarjeta bancaria proporcionado sea correcto")
                    banckCardConfirmDialog.setTipsContent(getCardNoContent(content, false))
                }
            }
        }

        mViewModel.mFinishFilter.observe(this) {
            if (it == true) {
                finishFilter()
            }
        }
    }

    //“xxx-xxx-xxxx-xxxx-xxx-x”
    //“xxxx-xxxx-xxxx-xxxx”
    fun getCardNoContent(no: String, is18: Boolean): String {
        if (is18) {
            var result = ArrayList<String>()
            var index = 0
            val thisSize = no.length
            var step = 3
            while (index in 0 until thisSize) {
                if (result.size == 2 || result.size == 3) {
                    step = 4
                } else {
                    step = 3
                }
                val end = index + step
                var coercedEnd = if (end > thisSize) thisSize else end
                result.add(no.substring(index, coercedEnd))
                index += step
            }
            return result.joinToString("-")
        } else {
            return no.chunked(4).joinToString("-")
        }
    }


    /**
     * 获取binding相关配置
     *
     * @return
     */
    override fun getDataBindingConfig(): BaseDataBindingConfig {
        return BaseDataBindingConfig(R.layout.activity_certify_information)
    }

    /**
     * 获取viewmodel Clazz
     *
     * @return
     */
    override fun initViewModelClazz(): Class<CertifyPersonInformationViewModel> {
        return CertifyPersonInformationViewModel::class.java
    }

    val tipsDialog by lazy {
        TipsDialog(
            title = "Nota",
            tips = "¿Está seguro/a de que desea salir del certificado? Completar los datos de autorización aumentará la posibilidad de conseguir el préstamo.",
            left = "Confirmar",
            right = "Cancelar"
        ).apply {
            setLeftListener {
                finishView()
            }
        }
    }

    fun finishFilter() {
        if (mComplete == "1") {
            finishView()
        } else {
            tipsDialog.show(supportFragmentManager, "")
        }
    }

    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (mComplete != "1") {
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                tipsDialog.show(supportFragmentManager, "")
                return false
            }
        }
        return super.onKeyDown(keyCode, event)
    }
}